package service.impl;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;

import service.File_service;
import util.FTPutil;
import util.PropertiesUtil;

@Service
public class File_service_impl implements File_service {
	private Logger log=LoggerFactory.getLogger(File_service_impl.class);

	@Override
	public String upload(MultipartFile file, String path) {
		String filename=file.getOriginalFilename();
		String fileExtensionName=filename.substring(filename.lastIndexOf(".")+1);
		
		String fileUploadName=UUID.randomUUID().toString()+"."+fileExtensionName;
		log.info("开始上传文件，上传文件名：{}，上传路径：{}，新文件名：{}",filename,path,fileUploadName);
		
		File fileDir=new File(path);
		if(!fileDir.exists()){
			fileDir.setWritable(true);
			fileDir.mkdirs();
		}
		
		File targetFile=new File(path,fileUploadName);
		try {
			file.transferTo(targetFile);
			//---到这里文件已经上传到项目的fileDir下
			FTPutil.uploadFile(Lists.newArrayList(targetFile));
			//--targetFile上传到FTP服务器上			
			targetFile.delete();
			//--删除项目的fileDir下的文件			
		} catch (IllegalStateException | IOException e) {
			log.error("上传文件失败",e);
			return null;
		}	
		return targetFile.getName();
	}

	@Override
	public void delete(String file) {
		String fileName=file.replace(PropertiesUtil.getProperty("ftp.http.prefix"),"");
		try {
			FTPutil.deleteFile(fileName);
		} catch (IOException e) {
			log.error("删除文件失败",e);
		}
	}

}
